/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.ActivateUserMailUtil;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.MD5;

/**
 * This action validates the request and set the corresponding attributes
 * required by the userRegister page
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class UserRegisterAction extends AbstractAction {

	private static final long serialVersionUID = 6781057487345139792L;
	// validate result
	public static final int CODE_ERROR = 0;
	public static final int PWD_ERROR = 1;
	public static final int USERNAME_USED = 2;
	public static final int EMAIL_USED = 3;
	public static final int CMD_ERROR = 4;
	public static final int REGISTER_ALLOWED = 5;

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String cmd = request.getParameter(PageConstants.CMD);
		if (PageConstants.PAGE_NAME_USERREGISTER.equals(cmd)) {

			HttpSession session = request.getSession(true);

			String userName = request.getParameter(PageConstants.USERNAME);

			String rand = request.getParameter("rand");
			String session_rand = (String) session.getAttribute("rand");
			if (rand != null && session_rand != null
					&& rand.equals(session_rand)) {
				String userPwd = request.getParameter("userPwd");
				String userPwd1 = request.getParameter("userPwd1");
				String userEmail = request
						.getParameter(PageConstants.USEREMAIL);
				if (userPwd1.equals(userPwd)) {
					UserService userService = new UserService();
					List<User> registered = userService.findByProperty("userName",
							userName);
					if (registered != null && registered.size() > 0) {
						return USERNAME_USED;
					}

					List<User> emailUsed = userService.findByProperty("email",
							userEmail);
					if (emailUsed != null && emailUsed.size() > 0) {
						return EMAIL_USED;
					}

					return REGISTER_ALLOWED;

				}

				else
					return PWD_ERROR;

			} else {
				return CODE_ERROR;
			}

		} else
			return CMD_ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (CODE_ERROR == validationResult || PWD_ERROR == validationResult
				|| EMAIL_USED == validationResult
				|| USERNAME_USED == validationResult) {
			request.setAttribute("init", "register");
			return "/";
		} else if (REGISTER_ALLOWED == validationResult)
			return PageConstants.PAGE_ACTION_MYINFO;
		else
			return PageConstants.ACTION_PATH_ERROR;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(true);
		String msg = null;
		String lang = (String) session.getAttribute(Messages.LANG);

		if (CODE_ERROR == validationResult) {
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_CODE_ERROR);
			} else {
				msg = Messages.getLabel(Messages.MSG_CODE_ERROR);
			}
		}
		if (PWD_ERROR == validationResult) {
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_PWD_ERROR);
			} else {
				msg = Messages.getLabel(Messages.MSG_PWD_ERROR);
			}
		}
		if (EMAIL_USED == validationResult) {
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_MAIL_SAME);
			} else {
				msg = Messages.getLabel(Messages.MSG_MAIL_SAME);
			}
		}
		if (USERNAME_USED == validationResult) {
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_USER_NAME_SAME);
			} else {
				msg = Messages.getLabel(Messages.MSG_USER_NAME_SAME);
			}
		}
		if (REGISTER_ALLOWED == validationResult) {

			String userName = request.getParameter(PageConstants.USERNAME);
			String userPwd = request.getParameter("userPwd");
			String userEmail = request.getParameter(PageConstants.USEREMAIL);
			User newUser = new User();
			UserService userService = new UserService();
			MD5 md5 = new MD5();
			newUser.setPwd(md5.getMD5ofStr(userPwd));
			newUser.setEmail(userEmail);

			newUser.setUserName(userName);

			newUser.setLastIp(request.getRemoteAddr());
			newUser.setRegTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			String activation = Config.getProperty(Config.REGISTER_ACTIVATION);
			if (Messages.TRUE.equals(activation))
				newUser.setIsLock(new Integer(1));
			else
				newUser.setIsLock(new Integer(0));
			userService.save(newUser);
			if (Messages.TRUE.equals(activation))
				ActivateUserMailUtil.sendActivationMail(request, userName,
						userEmail);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_REG_SUCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_REG_SUCESS);
			}
			// login
			session.setAttribute("login", Messages.TRUE);
			User sessionUser = userService.findByUserName(userName);
			sessionUser.setIsOnline(new Integer(1));
			sessionUser.setLoginNum(new Integer(sessionUser.getLoginNum()
					.intValue() + 1));
			sessionUser.setLastIp(request.getRemoteAddr());//
			sessionUser.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));//
			userService.merge(sessionUser);
			session.setAttribute(Messages.SESSION_USER, sessionUser);
		}

		request.setAttribute(Messages.MSG, msg);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
